package com.explorex.infra.puma.gateway.netty.ws.handler;


import com.explorex.infra.puma.gateway.netty.common.BaseSocketSession;
import com.explorex.infra.puma.gateway.netty.common.ChannelManager;
import com.explorex.infra.puma.gateway.netty.common.SpringContextUtils;
import com.explorex.infra.puma.gateway.netty.redis.BaseSessionRedis;
import com.explorex.infra.puma.gateway.netty.ws.WebSocketSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: JacceYang
 * @createTime: 2022/07/14 8:05 下午
 * @description: 与客户端之间的连接通道管理
 */
@ChannelHandler.Sharable
@Slf4j
public class ChannelManagerHandler extends ChannelInboundHandlerAdapter {

    private static BaseSessionRedis baseSessionRedis= SpringContextUtils.getBean("baseSessionRedis",BaseSessionRedis.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ChannelManager.getInstance().addSocketSession(ctx.channel(), new WebSocketSession(ctx.channel()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        BaseSocketSession socketSession = ChannelManager.getInstance().getSocketSession(ctx.channel());
        ChannelManager.getInstance().removeSocketSession(ctx.channel());
        // 如果抛出了异常，例如超时，也无需处理，直接上抛即可
        baseSessionRedis.removeSessionInfo(socketSession);
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }
}
